﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Net.Http.Json;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Cache.Repositories;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.DataBase;
using IMClient.Model.DTO;
using IMClient.Model.UI;
using IMClient.View;

namespace IMClient.ViewModels
{
    public partial class InitiateGroupChatWindowViewModel : ObservableObject
    {
        private readonly FriendCacheRepository _friendRepository;

        // 好友列表（所有好友）
        [ObservableProperty] private ObservableCollection<FriendViewModel> friends = new();

        // 已选中的好友列表
        [ObservableProperty] private ObservableCollection<FriendViewModel> selectedFriends = new();

        // 搜索关键字
        [ObservableProperty] private string? searchText;


        public string SelectedFriendsNumText => $"已添加 {SelectedFriends.Count} 个好友";

        // 过滤后的好友列表
        [ObservableProperty] private ObservableCollection<FriendViewModel> filteredFriends = new();

        public InitiateGroupChatWindowViewModel()
        {
            _friendRepository = FriendCacheRepository.Instance;
            _ = LoadFriendsAsync();
            FilteredFriends = new ObservableCollection<FriendViewModel>(Friends);

            SelectedFriends.CollectionChanged += (s, e) => { OnPropertyChanged(nameof(SelectedFriendsNumText)); };
        }


        private async Task LoadFriendsAsync()
        {
            try
            {
                string userId = User.UserId ?? throw new InvalidOperationException("用户ID不能为空");

                // 1. 从数据库加载好友列表
                var cachedFriends = await _friendRepository.GetCachedFriendsAsync(userId);
                UpdateFriendsList(cachedFriends);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载好友列表失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void UpdateFriendsList(List<FriendDataBase> friends)
        {
            Friends.Clear();
            foreach (var friend in friends)
            {
                Friends.Add(new FriendViewModel
                {
                    Id = friend.FriendId,
                    Name = friend.FriendName,
                    Avatar = friend.FriendAvatar,
                });
            }
        }
        
        [RelayCommand]
        private async Task CreatedGroupAsync()
        {
            if (SelectedFriends.Count < 2)
            {
                MessageBox.Show("至少需要选择两个好友", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                var group = new GroupDto
                {
                    Creator = User.UserId,
                    Members = SelectedFriends.Select(f => f.Id).ToArray(),
                };

                group.AdminId = [User.UserId];
                group.Members = group.Members.Prepend(User.UserId).ToArray();

                using (var client = new HttpClient())
                {
                    var response = await client.PostAsJsonAsync(
                        $"{NetWorkConfig.BaseUrl}/group/create",
                        group
                    );

                    var result = await response.Content.ReadFromJsonAsync<GroupApiResponse>();

                    if (result?.Code == "0000")
                    {
                        MessageBox.Show("创建群聊成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Application.Current.Windows.OfType<InitiateGroupChatWindow>().FirstOrDefault()?.Close();
                        // 更新群组聊天页表
                        var contactsViewModel = ChatWindowViewModel.Instance.GetContactsViewModel();
                        contactsViewModel?.JoinGroupAccept(User.UserId, new GroupViewModel
                        {
                            Id = result.Data!.GroupId,
                            Name = result.Data!.GroupName,
                            Avatar = result.Data!.GroupAvatar,
                            Creator = result.Data!.Creator
                        });
                    }
                    else
                    {
                        MessageBox.Show($"创建群聊失败: {result?.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建群聊失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void AddToSelectedFriends(FriendViewModel friend)
        {
            if (!SelectedFriends.Contains(friend))
            {
                SelectedFriends.Add(friend);
            }
        }

        public void RemoveFromSelectedFriends(FriendViewModel friend)
        {
            if (SelectedFriends.Contains(friend))
            {
                SelectedFriends.Remove(friend);
            }
        }

        partial void OnSearchTextChanged(string? value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                FilteredFriends = new ObservableCollection<FriendViewModel>(Friends);
            }
            else
            {
                FilteredFriends = new ObservableCollection<FriendViewModel>(
                    Friends.Where(f => f.Name.Contains(value))
                );
            }
        }
    }
}